package com.bstek.urule.springboot.utils;

import com.bstek.urule.Utils;
import com.bstek.urule.runtime.KnowledgePackage;
import com.bstek.urule.runtime.KnowledgeSession;
import com.bstek.urule.runtime.KnowledgeSessionFactory;
import com.bstek.urule.runtime.response.RuleExecutionResponse;
import com.bstek.urule.runtime.service.KnowledgeService;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class URuleUtil {

    public static Object execute(String id, Object... facts) {
        return execute(id, new HashMap<>(), facts);
    }
    public static Object execute(String id, Map<String, Object> params, Object... facts) {
        //从Spring中获取KnowledgeService接口实例
        KnowledgeService service=(KnowledgeService) Utils.getApplicationContext().getBean(KnowledgeService.BEAN_ID);
        KnowledgePackage knowledgePackage;
        try {
            //通过KnowledgeService接口获取指定的资源包"id"
            knowledgePackage = service.getKnowledge(id);
            //通过取到的KnowledgePackage对象创建KnowledgeSession对象
            KnowledgeSession session= KnowledgeSessionFactory.newKnowledgeSession(knowledgePackage);
            //将业务数据（变量）插入到KnowledgeSession中
            if(facts.length > 0) {
                for (Object fact : facts) {
                    session.insert(fact);
                }
            }
            //执行所有满足条件的规则
            RuleExecutionResponse ruleExecutionResponse = session.fireRules(params);
            return session.getParameter("result");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
